/**
 * @projectName base-yl
 * @package com.base.yl.cloudwechat.config.filter
 * @className com.base.yl.cloudwechat.config.filter.HeadParseFilter
 */
package com.answer.wx.gateway.config.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HeadParseFilter
 * @description 请求头拦截器
 * @author answer_wx
 * @date 2022/8/4 18:16
 * @version 1.0
 */
@Component
@Order(1)
@Slf4j
public class HeadParseFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        parse(httpServletRequest);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void parse(HttpServletRequest request) {
        String openId = request.getHeader("X-WX-OPENID");
        HttpHeader httpHeader = new HttpHeader();
        if (openId != null) {
            httpHeader.setOpenid(openId);
            RequestInfoHolder.newRequest(httpHeader);
        } else {
            RequestInfoHolder.newRequest(null);
        }
    }
}